package com.bawei.java.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author : yaotianxue
 * @Time : On 2023/5/24 16:26
 * @Description : Single
 */
public class Single {
    private Single(){}
    //无可见性，线程去内存读取一份拷贝在区域内，线程1修改数据，线程2不会立马得知
    //可见性：线程直接操作内存，线程1修改数据，线程2会立马得知
    private static Single single;//共享变量，无可见，无有序性
//    public static Single getInstance(){
//        if(single == null){
//            synchronized (Single.class){//锁对象Single.class  Single.class 一直是同一把锁
//                if(single == null){
//                    single = new Single();
//                }
//            }
//        }
//        return single;
//    }
    private static Lock mLock = new ReentrantLock();

    public static Single getInstance(){
        if(single == null){
            mLock.lock();//上锁
                    try {
                        if(single == null){
                            single = new Single();
                        }
                    }catch (Exception e){

                    }finally {//无论是否报错，肯定会执行
                        mLock.unlock();//解锁
                    }


        }
        return single;
    }
}
